package com.atguigu.tingshu.user.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.j2objc.annotations.AutoreleasePool;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

/**
 * title:
 * author: zgl
 * date: 2024/3/18
 * description：
 */
@Component
public class UserListener {

    @Autowired
    private UserPaidAlbumMapper paidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper paidTrackMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserVipServiceMapper vipServiceMapper;

    @Resource
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @KafkaListener(topics = KafkaConstant.QUEUE_USER_PAY_RECORD)
    public void updateInfos(String msg, Acknowledgment ack) {
        if (StringUtils.isBlank(msg)) {
            ack.acknowledge();
            return;
        }
        //获取消息对象
        UserPaidRecordVo recordVo = JSON.parseObject(msg, UserPaidRecordVo.class);
        if (recordVo == null) {
            ack.acknowledge();
            return;
        }
        //判断订单类型
        String orderNo = recordVo.getOrderNo();
        List<Long> ids = recordVo.getItemIdList();
        Long userId = recordVo.getUserId();
        if (CollectionUtils.isEmpty(ids) && StringUtils.isBlank(orderNo) && userId == null) {
            return;
        }
        switch (recordVo.getItemType()) {
            //新增购买整专辑信息
            case SystemConstant.ORDER_ITEM_TYPE_ALBUM:
                //查询是否有记录
                UserPaidAlbum userPaidAlbum = this.paidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getOrderNo, orderNo));
                if (userPaidAlbum != null) {
                    return;
                }
                userPaidAlbum = new UserPaidAlbum();
                userPaidAlbum.setUserId(userId);
                userPaidAlbum.setOrderNo(orderNo);
                userPaidAlbum.setAlbumId(ids.get(0));
                this.paidAlbumMapper.insert(userPaidAlbum);
                ack.acknowledge();
                break;
            //新增购买声音套餐信息
            case SystemConstant.ORDER_ITEM_TYPE_TRACK:
                //查询是否有记录
                List<UserPaidTrack> userPaidTracks = this.paidTrackMapper.selectList(new LambdaQueryWrapper<>(UserPaidTrack.class)
                        .eq(UserPaidTrack::getOrderNo, orderNo));
                if (!CollectionUtils.isEmpty(userPaidTracks)) {
                    return;
                }
                //查询声音的所属专辑id
                Result<TrackInfo> trackInfoResult = this.trackInfoFeignClient.getTrackInfo(ids.get(0));
                Assert.notNull(trackInfoResult, "新增购买声音套餐信息：获取声音信息失败！");
                TrackInfo trackInfo = trackInfoResult.getData();
                Assert.notNull(trackInfoResult, "新增购买声音套餐信息：获取声音信息失败！");
                ids.forEach(id -> {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setUserId(userId);
                    userPaidTrack.setTrackId(id);
                    userPaidTrack.setOrderNo(orderNo);
                    userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                    this.paidTrackMapper.insert(userPaidTrack);
                });
                ack.acknowledge();
                break;
            //更新vip信息  user_info  user_vip_service
            case SystemConstant.ORDER_ITEM_TYPE_VIP:
                //查询是否有记录
                UserVipService userVipService = this.vipServiceMapper.selectOne(new LambdaQueryWrapper<UserVipService>()
                        .eq(UserVipService::getOrderNo, orderNo));
                if (userVipService != null) {
                    return;
                }
                //根据userId查询当前用户是否是vip
                UserInfo userInfo = this.userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getId, userId));
                if (userInfo == null) {
                    return;
                }
                //查询vip套餐信息
                VipServiceConfig vipServiceConfig = this.vipServiceConfigMapper.selectOne(new LambdaQueryWrapper<VipServiceConfig>()
                        .eq(VipServiceConfig::getId, ids.get(0)));
                if (vipServiceConfig == null) {
                    return;
                }
                userVipService = new UserVipService();
                userVipService.setUserId(userId);
                userVipService.setOrderNo(orderNo);
                Date startTime = new Date();
                Date endTime = LocalDateTime.fromDateFields(startTime).plusMonths(vipServiceConfig.getServiceMonth()).toDate();
                if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(new Date())) {
                    //已经是vip
                    LocalDateTime startTimeType = LocalDateTime.fromDateFields(userInfo.getVipExpireTime()).plusDays(1);
                    startTime = startTimeType.toDate();
                    endTime = startTimeType.plusMonths(vipServiceConfig.getServiceMonth()).toDate();
                }
                //新增user_vip_service
                userVipService.setExpireTime(endTime);
                userVipService.setStartTime(startTime);
                this.vipServiceMapper.insert(userVipService);
                //更新user_info
                userInfo.setIsVip(1);
                userInfo.setVipExpireTime(endTime);
                this.userInfoMapper.updateById(userInfo);
                ack.acknowledge();
                break;
        }
    }
}
